#!/usr/bin/perl -w
#Purpose: to locate %Min peaks in %MinMax data
#user enters filename of %MinMax file
#scans %MinMax results and replaces each %MinMax value with "0" if position is a peak and "1" if position is not a peak
#peak is defined as the smallest value in a window of 11 (where the given position is the center codon), if the window is equal to or below a specified cutoff
#user enters cutoff value: depends on RRT analysis of the organism 


$inputfile = $ARGV[0];
$cutoff = $ARGV[1];

open(MMVFILE,$inputfile);
$output = "peaks-" . $inputfile;
open(OUTPUT,">$output");
 
$sequences = 0;

while ($line = <MMVFILE>){
		#%MinMax file is fasta formatted, so header lines begin with ">"
		if ($line =~ ">"){++$sequences;push(@SequenceHeaders,$line);}
		elsif ($line =~ ","){chomp $line;push(@mmvdata,$line);}}

$Headers = scalar @SequenceHeaders;
$Data = scalar @mmvdata;
unless ($Headers == $Data){print "Error: mismatched between number of sequence headers and lines of sequence data\n";exit;}

foreach $sequenceMMV (@mmvdata){
	$header = shift @SequenceHeaders;
	print OUTPUT $header;
	@MMVvalues = split(",",$sequenceMMV);
	$ArrayPosition = 0;
	$NumWindows = scalar @MMVvalues;
	$LastArrayPosition = $NumWindows - 1; 
	foreach $MMVvalue (@MMVvalues){
		if ($MMVvalue > $cutoff){print OUTPUT "1,";}
		else  {
			if (($ArrayPosition -5) < 0){$start = 0;}
			else {$start = $ArrayPosition -5;}
			if (($ArrayPosition + 5) > $LastArrayPosition){$end = $LastArrayPosition;}
			else {$end = $ArrayPosition + 5;}
			$place = $start;
			#print "start $start end $end\n";
			#set initial value that's impossibly large
			$min = 1000;
			until ($place == $end){
				$MMVcheck = $MMVvalues[$place];
				if ($MMVcheck < $min){$min = $MMVcheck;}
				++$place;}
			if ($min < $MMVvalue){print OUTPUT "1,";}
			else {print OUTPUT "0,";
				#print "minimum: $min\n";
			}
		}
	++$ArrayPosition;
	}
	print OUTPUT "\n";
}

print "MMV data for $sequences sequences\n";

close MMVFILE;
close OUTPUT;
exit;
